
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.AzureOpenAI;

namespace AiDrawingWinform
{
    internal static class Program
    {
        #region Private Methods

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            ApplicationConfiguration.Initialize();

            var azureOpenAiApiKey = Environment.GetEnvironmentVariable("azureopenaiapikey") ?? throw new InvalidOperationException("Azure OpenAI API key not found");
            var azureOpenAiEndpoint = Environment.GetEnvironmentVariable("azureopenaiendpoint") ?? throw new InvalidOperationException("Azure OpenAI endpoint not found");
            var azureOpenAiModel = Environment.GetEnvironmentVariable("azureopenaimodel") ?? throw new InvalidOperationException("Azure OpenAI model not found");

            var serviceProvider = new ServiceCollection()
                .AddSingleton<IAgent, Agent>()
                .AddSingleton<IChatCompletionService>(_ => 
                    new AzureOpenAIChatCompletionService(azureOpenAiModel,
                        azureOpenAiEndpoint, azureOpenAiApiKey))
                .AddSingleton<CanvasPlugin>()
                .AddTransient(sp =>
                {
                    KernelPluginCollection plugins = [];
                    plugins.AddFromObject(sp.GetRequiredService<CanvasPlugin>());
                    return new Kernel(sp, plugins);
                })
                .AddMediatR(cfg =>
                {
                    cfg.RegisterServicesFromAssemblyContaining<FrmMain>();
                    cfg.Lifetime = ServiceLifetime.Singleton;
                })
                .BuildServiceProvider();

            Application.Run(new FrmMain(serviceProvider.GetRequiredService<IAgent>()));
        }

        #endregion Private Methods
    }
}